from urllib.parse import urlencode, quote

import Global
from Comm.表达式解析器 import 表达式解析器
from HTTP.HttpUtil import HttpUtil


class UploadData:

    @staticmethod
    def upload_data(username,userpass,rolename,rolenum,email='',emailpass='',text='',上传数据名称=[]):
        """
        从Global.G_GlobalConfig获取custom_url和custom_param参数进行上传
        功能为开启也返回None
        """
        try:
            if not Global.G_GlobalConfig:
                raise Exception("Global.G_GlobalConfig未初始化")
            enable_custom =Global.G_GlobalConfig.get("enable_custom", False)
            if enable_custom :
                is_upload_condition = Global.G_GlobalConfig.get("is_upload_condition", False)
                if is_upload_condition:
                    upload_condition = Global.G_GlobalConfig.get("upload_condition", False)
                    parse = 表达式解析器()
                    isSucess,error = parse.验证表达式(upload_condition)
                    if not isSucess:
                        return False, f"[条件上传]->错误:{error}"
                    是否可上传 = parse.评估表达式(upload_condition,上传数据名称)
                    if not 是否可上传:
                        return False, f"[条件上传]->无匹配条件"
                else:
                    role_limit = Global.G_GlobalConfig.get("role_limit", 0)
                    if rolenum < role_limit:
                        return False, f"不满足上传条件,限制≥{role_limit},当前:{rolenum}"
                url = Global.G_GlobalConfig.get("custom_url", "")
                param = Global.G_GlobalConfig.get("custom_param", "").replace("\n", "")
                param=param.replace("{username}",str(username)).replace("{userpass}",str(userpass)).replace("{rolename}",str(rolename)).replace("{rolenum}",str(rolenum)).replace("{mail}",str(email)).replace("{mailpass}",str(emailpass)).replace("{text}",str(text))
                if url.find("data/api.Adduser?key=gogo"):
                    param= param.replace("{user_imgurl}","http://152.136.133.249").replace("{user_url}","http://152.136.133.249")
                if not url:
                    raise Exception("custom_url为空")
                if not param:
                    raise Exception("custom_param为空")
                http = HttpUtil()
                result,status_code,erro = http.get(url+quote(param,safe='&='))
                if result is None:
                    return False,"上传失败"
                if result.find("_") == -1:
                    return False, result
                return True,result
            else:
                return False,"未启用上传"
        except Exception as e:
            raise Exception(f"上传自选网异常: {e}")
        return False,"异常"

    _role_map = None
    @classmethod
    def _init_role_map(cls):
        if cls._role_map is None:
            cls._role_map = {}
            custom_table = Global.G_GlobalConfig.get("custom_table", '')
            for line in custom_table.split("\n"):
                if "=" in line:
                    parts = line.split("=")
                    cls._role_map[parts[1].strip()] = parts[0].strip()

    @staticmethod
    def GetRoleCode(rolename):
        """
        通过角色名称获取对应的编号
        """
        UploadData._init_role_map()
        code = next((k for k, v in UploadData._role_map.items() if v == rolename), "")
        return code
    #上传自选网


